package com.shitou.shitoumember.controller;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;

import com.shitou.shitoumember.vo.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * class detail:
 *  // 创建一个用户，加入一批商品
 * @author 石头人
 */
@SuppressWarnings("all")
@RestController
@RequestMapping("/spider")
public class CreateMemberUtils {

    private String fileName = "loginMember.txt";

    public static void main(String[] args) throws IOException {
//        new CreateMemberUtils().doRegister();

        CreateMemberUtils createMemberUtils = new CreateMemberUtils();
        List<RegisterVo> data = createMemberUtils.createData();
        int i = 0;
        for (RegisterVo datum : data) {
            i++;
//            if ( i == 11 ) {
//                i++;
//            }
            LoginVo loginVo = new LoginVo();
            loginVo.setAccount(datum.getAccount());
            loginVo.setPassword(datum.getPassword());
            createMemberUtils.doLogin(loginVo, i);
        }

    }


    @RequestMapping("/spider")
    public String spider() throws IOException {
        new CreateMemberUtils().doRegister();
        return "爬取所有数据成功";
    }

    private String api_url = "http://localhost:8080/api/shitou-member/shitoumember/member/register";
    private String addProduct_url = "http://localhost:8080/api/shitou-product/shitouproduct/spuinfo/editMemberProduct";

    public void doRegister() throws IOException {
        List<RegisterVo> registerList = createData();
        Map<String, String> categoryMap = new HashMap<>();
        Map<String, String> brandMap = new HashMap<>();
        Map<String, Long> attrMap = new HashMap<>();

        categoryMap.put("225", "手机");  // 4
        categoryMap.put("233", "蓝牙耳机");  // 17
        categoryMap.put("366", "智能手表");   // 18
        categoryMap.put("387", "学生平板");   // 19

        attrMap.put("225", 4L);  // 4
        attrMap.put("233", 17L);  // 17
        attrMap.put("366", 18L);   // 18
        attrMap.put("387", 19L);   // 19


        // 创建用户
        for (RegisterVo vo : registerList) {
            HttpURLConnection conn = register(vo);
            int responseCode = conn.getResponseCode();
            // 注册成功
            if ( responseCode == 2001 ){
                // 获取会员 id
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String input_line = null;
                while ((input_line = in.readLine()) != null) {
                    ReponseVo reponseVo = JSON.parseObject(input_line, ReponseVo.class);
                    // 开始添加商品
                    Set<String> strings = categoryMap.keySet();
                    for (String key : strings) {
                        String value = categoryMap.get(key);
                        Long attrId = attrMap.get(key);
                        List<String> list = spiderProduct(value, 10);
                        System.out.println(list);
                        for (String item : list) {
                            createProduct(key, 1, attrId, reponseVo.getId(),item);
                        }
                    }
                }
            }
        }

    }


    public void addProduct(String jsonString){
        try {
            URL url = new URL(addProduct_url);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setDoOutput(true);
            OutputStream ots = conn.getOutputStream();
            ots.write(jsonString.getBytes(StandardCharsets.UTF_8));
            ots.flush();
            int responseCode = conn.getResponseCode();
            if ( responseCode == 200 ){
                System.out.println("提交成功");
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public void register(RegisterVo vo, Integer a){
        HttpURLConnection register = register(vo);
    }

    /**
     * 开始注册
     * @param jsonString
     * @return
     */
    public HttpURLConnection register(RegisterVo vo){
        URL url = null;
        HttpURLConnection conn = null;
        try {
            url = new URL(api_url);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setDoOutput(true);
            OutputStream ots = conn.getOutputStream();
            String jsonData = getJSONData(vo);
            ots.write(jsonData.getBytes(StandardCharsets.UTF_8));
            ots.flush();
            ots.close();
            return conn;
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 将带注册对象转换为json数据
     * @param registerVo
     * @return
     */
    public String getJSONData(Object vo){
        Gson gson = new Gson();
        String jsonString = gson.toJson(vo);
        return jsonString;
    }


    /**
     * 创建用户数据
     * @return
     */
    public List<RegisterVo> createData(){
        List<RegisterVo> list = new ArrayList<>();
        RegisterVo register = null;

        for ( int i = 1; i <= 1000; i ++){
            register = new RegisterVo();
            register.setAccount(String.valueOf((1300000000L+i)));
            register.setEmail(String.valueOf((1300000000L+i))+"@qq.com");
            register.setPassword(String.valueOf((1300000000L+i)));
            list.add(register);
        }
        return list;
    }


    public void createProduct(String categoeyId, int brandId, Long attrId, Long memberId, String item){
        if ( memberId == null || memberId == 0 ){
            return;
        }
        String[] split = item.split("我的索引");
        if ( split[1].length() <= 0 ){
            return;
        }

        ProductInfoVo vo = new ProductInfoVo();
        AttrInfo attrInfo = new AttrInfo();
        attrInfo.setId(Math.toIntExact(attrId));
        attrInfo.setName("成色");
        Random random = new Random();
        String[] value = new String[]{"99成新", "95成新", "9成新", "85成新"};
        attrInfo.setValue(value[random.nextInt(4)]);
        vo.setAllAttr(new AttrInfo[]{attrInfo});
        vo.setId(Math.toIntExact(memberId));
        vo.setBrandId(Math.toIntExact(brandId));
        vo.setCategoryId(Math.toIntExact(Long.parseLong(categoeyId)));

        vo.setPrice(BigDecimal.valueOf(Double.valueOf(split[2])));
        vo.setSpuTitle(split[0]);
        vo.setBrandSellName("");
        vo.setSpuDetail(split[0]);
        vo.setImageUrls(split[1].split(";"));

        String jsonData = getJSONData(vo);
        // 开始上传
        addProduct(jsonData);
    }


    /**
     * 爬取商品
     */
    public List<String> spiderProduct(String keyword, int pages){
        List<String> items = new ArrayList();
        try {
            // 目标地址
            String url = "https://search.jd.com/Search?keyword="+keyword+"&enc=utf-8&wq="+keyword+"&pvid=4f4b845c86a4492ca190f3119a2910b6";
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:72.0) Gecko/20100101 Firefox/72.0");
            // 获取页面文档对象
            Document doc = Jsoup.connect(url).get();
            // 获取商品列表
            Elements itemList = doc.select(".gl-warp .gl-item ");
            Elements select1 = itemList.select(".ps-wrap .ps-main .ps-item a img");
            System.out.println(select1);
            for (Element item : itemList) {
                // 获取商品标题
                String title = item.select(".p-name").text();
                // 获取商品价格
                Double price = Double.parseDouble(item.select(".p-price i").text().equals("暂无报价")? String.valueOf(999.00) :item.select(".p-price i").text());
                // 获取相应对应的图片
                StringJoiner allImage = new StringJoiner("");
                Elements select = item.select(".ps-wrap .ps-main .ps-item");
                for (Element element : select) {
                    allImage.add(element.select("a img").attr("data-lazy-img")+";");
                }
                // 将商品信息保存到List中
                items.add(title + "我的索引" + allImage + "我的索引" + price + "我的索引");
            }
            return items;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 创建的用户直接登录， 用来测试抢商品
     */
    public void doLogin(LoginVo loginVo, int memberId){
        try {
            // 做登录的url
            String urlString = "http://localhost:8080/api/shitou-member/shitoumember/member/login";
            String projuctPath = System.getProperty("user.dir");
            // 文件路径
            File file = new File(projuctPath + "\\shitou-member\\src\\main\\resources\\static\\mytext\\"+fileName);
            // 随机读写文件
            RandomAccessFile raf = new RandomAccessFile(file,"rw");
            // 指定指针为开始位置
            raf.seek(0);
            String jsonData = getJSONData(loginVo);
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setDoOutput(true);
            OutputStream ots = conn.getOutputStream();
            ots.write(jsonData.getBytes(StandardCharsets.UTF_8));

            int responseCode = conn.getResponseCode();
            if( responseCode == 200 ){
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String input_line = null;
                StringJoiner joiner = new StringJoiner("");
                while ((input_line = in.readLine()) != null) {
                    System.out.println(input_line + " : " + loginVo.getAccount());
                    LoginReponseVo loginReponseVo = JSON.parseObject(input_line, LoginReponseVo.class);
                    String row = loginReponseVo.getToken();
                    // 买家，商品id，商品价格，登录token凭证
                    joiner.add(memberId+",1"+",2099,"+loginReponseVo.getToken());
                    raf.seek(raf.length());
                    raf.write(joiner.toString().getBytes());
                    raf.write("\r\n".getBytes());
                }
                raf.close();
            }
            ots.flush();
            ots.close();
        } catch ( Exception e){
            e.printStackTrace();
        }
    }

}
